<template>
  <el-scrollbar class="h-full">
    <el-table class="flex-1" :data="tableData" style="width: 100%">
      <el-table-column prop="displayName" label="生理参数" />
      <el-table-column prop="description" label="描述" />

      <el-table-column label="安全范围最小值">
        <template #default="scope">
          <div @dblclick="handleEditField(scope.row, 'normalMin')">
            <el-input
              ref="editInput"
              v-if="scope.row.editingField === 'normalMin'"
              v-model="scope.row.normalMin"
              @blur="handleSaveField(scope.row, 'normalMin')"
              @keyup.enter="handleSaveField(scope.row, 'normalMin')"
              placeholder="请输入最小值"
              type="number"
              :min="0"
              autofocus
            />
            <span v-else>{{ scope.row.normalMin ?? 0 }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="安全范围最大值">
        <template #default="scope">
          <div @dblclick="handleEditField(scope.row, 'normalMax')">
            <el-input
              ref="editInput"
              v-if="scope.row.editingField === 'normalMax'"
              v-model="scope.row.normalMax"
              @blur="handleSaveField(scope.row, 'normalMax')"
              @keyup.enter="handleSaveField(scope.row, 'normalMax')"
              placeholder="请输入最大值"
              type="number"
              :min="0"
              autofocus
            />
            <span v-else>{{ scope.row.normalMax ?? 0 }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="严重不足阈值">
        <template #default="scope">
          <div @dblclick="handleEditField(scope.row, 'criticalMin')">
            <el-input
              ref="editInput"
              v-if="scope.row.editingField === 'criticalMin'"
              v-model="scope.row.criticalMin"
              @blur="handleSaveField(scope.row, 'criticalMin')"
              @keyup.enter="handleSaveField(scope.row, 'criticalMin')"
              placeholder="请输入阈值"
              type="number"
              :min="0"
              autofocus
            />
            <span v-else>{{ scope.row.criticalMin ?? 0 }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="严重超标阈值">
        <template #default="scope">
          <div @dblclick="handleEditField(scope.row, 'criticalMax')">
            <el-input
              ref="editInput"
              v-if="scope.row.editingField === 'criticalMax'"
              v-model="scope.row.criticalMax"
              @blur="handleSaveField(scope.row, 'criticalMax')"
              @keyup.enter="handleSaveField(scope.row, 'criticalMax')"
              placeholder="请输入阈值"
              type="number"
              :min="0"
              autofocus
            />
            <span v-else>{{ scope.row.criticalMax ?? 0 }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="严重超标持续时间(s)">
        <template #default="scope">
          <div @dblclick="handleEditField(scope.row, 'criticalTime')">
            <el-input
              ref="editInput"
              v-if="scope.row.editingField === 'criticalTime'"
              v-model="scope.row.criticalTime"
              @blur="handleSaveField(scope.row, 'criticalTime')"
              @keyup.enter="handleSaveField(scope.row, 'criticalTime')"
              placeholder="请输入持续时间"
              type="number"
              :min="0"
              autofocus
            />
            <span v-else>{{ scope.row.criticalTime ?? 0 }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </el-scrollbar>
</template>

<script setup lang="ts">
import { reactive, onMounted, watch, ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { debounce } from 'lodash'
import { getPhysiologicalSettings } from '@/api/settings'
import { useUserStore } from '../../../store/user'
import { savePhysiologicalSettings } from '@/api/physiological'

const userStore = useUserStore()

const tableData = ref([])
// const settingsForm = ref()
const isInitialized = ref(false)

/**
 * 加载现有设置
 */
const loadSettings = async () => {
  try {
    const settings = await getPhysiologicalSettings()
    // 为每一行数据添加编辑状态属性
    if (settings.data && Array.isArray(settings.data.list)) {
      tableData.value = settings.data.list.map((item) => ({
        ...item,
        isEditing: false, // 添加编辑状态属性
        editingField: null // 添加当前正在编辑的字段名
      }))
    } else {
      tableData.value = []
      ElMessage.warning('未获取到设置数据')
    }
  } catch (error) {
    ElMessage.error('获取设置失败')
  }

  // 等待所有响应式更新完成后再激活监听器
  await nextTick()
  isInitialized.value = true
}

/**
 * 处理双击编辑字段
 */
const editInput = ref(null)
const handleEditField = (row: any, fieldName: string) => {
  row.editing = fieldName
  nextTick(() => {
    editInput.value?.focus()
  })
  // 将所有行的编辑状态重置
  tableData.value.forEach((item: any) => {
    if (item !== row) {
      item.editingField = null
      item.isEditing = false
    } else {
      // 如果是当前行，重置其他可能正在编辑的字段
      item.isEditing = false
    }
  })
  // 设置当前行的当前字段为编辑状态
  row.editingField = fieldName
}

/**
 * 保存字段修改
 */
const handleSaveField = async (row, fieldName: string) => {
  // 退出编辑状态
  row.editingField = null

  try {
    // 验证输入值是否为有效数字
    const fieldValue = Number(row[fieldName])
    if (isNaN(fieldValue) || fieldValue < 0) {
      ElMessage.warning(`请输入有效的${getFieldLabel(fieldName)}`)
      loadSettings()
      return
    }

    // 发送保存请求
    await savePhysiologicalSettings({
      id: row.id,
      normalMin: row.normalMin,
      normalMax: row.normalMax,
      criticalMin: row.criticalMin,
      criticalMax: row.criticalMax,
      criticalTime: row.criticalTime
    })

    ElMessage.success('设置保存成功')
  } catch (error) {
    ElMessage.error('保存设置失败，请重试')
  }
  loadSettings()
}

/**
 * 获取字段对应的中文标签
 */
const getFieldLabel = (fieldName: any) => {
  const fieldLabels = {
    normalMin: '安全范围最小值',
    normalMax: '安全范围最大值',
    criticalMin: '严重不足阈值',
    criticalMax: '严重超标阈值',
    criticalTime: '严重超标持续时间'
  }
  return fieldLabels[fieldName] || '值'
}

/**
 * 保存设置
 */
// const saveSettings = async (data) => {
//   try {
//     await savePhysiologicalSettings(data)
//     ElMessage.success('设置保存成功')
//   } catch (error) {
//     console.error('保存设置失败:', error)
//     ElMessage.error('保存设置失败，请重试')
//   }
// }

// 创建防抖保存函数
// const debouncedSaveSettings = debounce(saveSettings, 500)

/**
 * 监听表单变化，自动保存
 */
// watch(
//   () => settingsForm,
//   () => {
//     if (isInitialized.value) {
//       debouncedSaveSettings()
//     }
//   },
//   { deep: true }
// )

watch(
  () => userStore.token,
  (newToken) => {
    if (newToken) {
      loadSettings()
    }
  }
)

onMounted(() => {
  if (userStore.token) {
    loadSettings()
  }
})
</script>

<style scoped lang="scss">
.blood-pressure-group {
  @apply flex flex-col gap-4;
}

.pressure-item {
  @apply flex items-center gap-4;
}

.pressure-label {
  @apply text-gray-600 text-sm;
}
</style>
